<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
      #canvas {
          background: #f1f1f1;
      }
      #hovered-color, #selected-color {
          width: 100px;
          height: 100px;
      }
  </style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<br>
<span>hovered-color</span>
<div id="hovered-color">

</div>
<br>
<span>selected-color</span>
<div id="selected-color"></div>
<script>
    window.onload = () => {
        var img = new Image();
        img.crossOrigin = 'anonymous';
        img.src = 'https://net-cloud.xhey.top/shareJigsaw/photos/72DD7D6A-5D34-4BA5-A564-4248A21BE8CC.jpg';
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        img.onload = function() {
            ctx.drawImage(img, 0, 0);
            img.style.display = 'none';
        };
        var hoveredColor = document.getElementById('hovered-color');
        var selectedColor = document.getElementById('selected-color');


        function pick(event, destination) {
            var x = event.layerX;
            var y = event.layerY;
            // 得到当前2*4面积内的像素
            var pixel = ctx.getImageData(x, y, 2, 4);
            console.log('getImageData:',pixel)
            var data = pixel.data;

            // 得到第3*1列的第一个像素
            console.log('3*1列数据:',pixel.data[(2*pixel.width*4)+(0*4)])
            // 得到第4*2列的第一个像素
            console.log('4*2列数据:',pixel.data[(3*pixel.width*4)+(1*4)])
            //所以 根据行、列读取某像素点的R/G/B/A值的公式： 0/1/2/3 表示 RGBA各个数值
            // // n行*m列数据: pixel.data[((n-1)*pixel.width*4)+((m-1)*4) + 0/1/2/3]

            const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;
            destination.style.background = rgba;
            destination.textContent = rgba;

            // 你可以用putImageData()方法去对场景进行像素数据的写入。
            // ctx.putImageData(myImageData, dx, dy);  dx和dy参数表示你希望在场景内左上角绘制的像素数据所得到的设备坐标。
            ctx.putImageData(pixel, 50, 50);

            return rgba;
        }

        canvas.addEventListener('mousemove', function(event) {
            pick(event, hoveredColor);
        });
        canvas.addEventListener('click', function(event) {
            pick(event, selectedColor);
        });

    }

</script>
</body>
</html>
